from django.db import models
from annoying.functions import get_object_or_None
from django.contrib.contenttypes.models import ContentType

import core
from core.models import User
from core.models.auth.providers import Internal


class InternalCredential(models.Model):
    login = models.CharField(max_length=255, unique=True)
    password_hash = models.CharField(max_length=255)

    class Meta:
        app_label = core.APP_LABEL

    class AlreadyExists(Exception):
        pass

    def __unicode__(self):
        return '{0} {1}'.format(self.login, self.password_hash)
    
    
    def authenticate(self):
    
        credential = get_object_or_None(InternalCredential,
            login=self.login,
            password_hash=self.password_hash)
    
        if credential is not None:
            content_type = ContentType.objects.get_for_model(credential)
            return User.objects.get(auth__content_type=content_type,
                                    auth__credential_id=credential.id)
    
        return None
    
    
    def register(self):
    
        if InternalCredential.objects.filter(login=self.login).exists():
            raise InternalCredential.AlreadyExists()
    
        credential = InternalCredential.objects.create(
            login=self.login,
            password_hash=self.password_hash)
    
        user = User.objects.create(name=credential.login)
        user.auth_set.create(provider=Internal, credential=credential)
    
        return user